﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using Jacaranda.Data;

namespace Jacaranda.Model
{
    public class Update : ParameterGenerationNode
    {
        public Update(string propertyName, object value) :
            this(new AbstractProperty(propertyName), value)
        {
        }

        public Update(AbstractProperty property, object value)
        {
            Property = property;

            if (value is ComparableNode)
            {
                ExpressionValue = value as ComparableNode;
            }
            else
            {
                ConstantValue = value;
            }
        }


        public AbstractProperty Property { get; set; }

        public ComparableNode ExpressionValue { get; set; }

        public object ConstantValue { get; set; }


        internal override string GenerateSql(Type propertyEntityType)
        {
            if (!object.Equals(ExpressionValue, null))
            {
                return string.Format("{0} = {1}", Property.Name, ExpressionValue.GenerateSql(propertyEntityType));
            }
            else
            {
                string parameterName = "conditionParameter" + ParameterIndex;

                DbParameter parameter = DataAccess.Create().CreateDbParameter();

                parameter.ParameterName = parameterName;
                parameter.Value = ConstantValue;

                Command.Parameters.Add(parameter);

                return string.Format("{0} = {1}", Property.Name, DataAccess.Create().CreateParameterizedExpression(parameterName));
            }
        }
    }
}
